package com.bird.framework.config;

import com.bird.common.constant.Constants;
import com.bird.framework.domain.StringToEnumConverterFactory;
import com.bird.framework.interceptor.DemoShowInterceptor;
import com.bird.framework.interceptor.RepeatSubmitInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.TimeZone;

/**
 * webmvc 配置
 *
 * @author: 625
 * @version: 2019年11月27日 9:24
 */
@Configuration
public class WebConverterConfig implements WebMvcConfigurer {

	@Autowired
	private RepeatSubmitInterceptor repeatSubmitInterceptor;

	@Autowired(required = false)
	private DemoShowInterceptor demoShowInterceptor;

	/**
	 * 时区配置
	 */
	@Bean
	public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() {
		return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault());
	}

	/**
	 * 枚举类的转换器 addConverterFactory
	 */
	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverterFactory(new StringToEnumConverterFactory());
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		/** 本地文件上传路径 */
		registry.addResourceHandler(Constants.System.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + BirdConfig.getProfile() + "/");

		/** swagger配置 */
		registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
	}

	/**
	 * 自定义拦截规则
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
		if (demoShowInterceptor != null) {
			registry.addInterceptor(demoShowInterceptor).addPathPatterns("/**");
		}
	}
}
